<%--
  Function: 
  User: PING
  Date: 2022/10/27

--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/xhr.js"></script>
</head>
<body>

<h3>Ajax演示</h3>
请选择选在国家： <select id="nation" name="nation" onchange="selectCity();">
              <option value="0">--</option>
                <option value="1">中国</option>
                <option value="2">美国</option>
                <option value="3">日本</option>
             </select><br>
请选择所喜爱的城市：
<select id="city" name="city">
                 <option value="0">--</option>
</select><br>
<hr>
<h3>您对这门课程的感兴趣吗？</h3>
<form id="rating-form">
    <input type="radio" name="rating" value="5">5
    <input type="radio" name="rating" value="4">4
    <input type="radio" name="rating" value="3">3
    <input type="radio" name="rating" value="2">2
    <input type="radio" name="rating" value="1">1
    <br>
    理由是：<br>
    <textarea id="comment" cols="20" rows="5" ></textarea><br>
    <input type="button" value="确定" onclick="doRateInJson();"/>
</form>
<div id="showMsg" style="border:1px solid green; display:none; width:50%">
</div>

<script>
    /**
     * @function: 获取对应的国家的城市列表
     */
    function selectCity() {

        // step1. get parameter
        var $nation = document.getElementById("nation") ;
        var nationId ;
        for (var i=0; i<$nation.options.length; i++) {
            if ($nation.options[i].selected) {
                nationId = $nation.options[i].value ;
                break ;
            }
        }
        // parameter string for passing data.
        var action = "selectCity"
        var paramStr = "action=" + action + "&nationId=" + nationId ;

        //step2. create XHR
        var xhr = createXMLRequest() ;
        // step3. XHR api: configuration request: url, method, headers,
        xhr.open(
            // method type:GET POST
            "GET",
            /*
             url: NativeAjaxServlet: contextRoot/ajax/nativeAjax
             passing data depends on method type:
             if method type is GET :
                  url += paramStr ;  (paramStr ::=  key1=value1&key2=value2&...)
              else if for POST:
                 ..
             */

            "/01_jspBasics/test/nativeAjax?" + paramStr,
            // asynchrous: true | false ;
            true // in default: true
        )

        // step4. XHR callback: set callback function (load and render data)
        xhr.onreadystatechange = function() {
            // the function was defined and binded to response events of state changes of XHR
            // xhr lifecycle: initialized, opened, sent, receiving, loaded
            // when xhr was on LOADED state, then the data could be rendered in given area.
            if (xhr.readyState == 0) {
                console.log("uninitialized.") ;
            } else if (xhr.readyState == 1) {
                console.log("opening") ;
            } else if (xhr.readyState == 2) {
                console.log("sent") ;
            } else if (xhr.readyState == 3) {
                console.log("receiving") ;
            } else if (xhr.readyState == 4) {
                console.log("loaded") ;
                // get server response successfully, but it could be normal and abnormal, (e.g. 304, 404, 500).
                if (xhr.status == 200) {
                    // got a normal response.
                    // response data:  xhr.responseText
                   //  Notation: 北京|上海|xxx|xxxx|xxxx
                    var cities = xhr.responseText.split("|") ;
                    console.log("got cities: " + cities) ;
                    // rendering data in options
                    var $selectCity = document.getElementById("city") ;
                    // clear options
                    $selectCity.options.length = 0 ;
                    cities.forEach(function(item, index) {
                        // create option element
                        var $newOption = document.createElement("option") ;
                        // set option value
                        $newOption.innerHTML = item ;
                        // append child to select father
                        $selectCity.appendChild($newOption) ;
                    })

                }

                }


        }
        // step5. send request
        xhr.send() ;

    }

    /**
     * @function: do rating
     */
    function doRate() {
        // 1. preparing parameters

        var $ratingForm = document.getElementById("rating-form");
        var ratingValue  ;
        // got rating value
        $ratingForm.rating.forEach(function(item,index) {
            if (item.checked) {
                ratingValue = item.value ;
            }
        })
        // got comment value
        var comment = document.getElementById("comment").value ;

        if (ratingValue.trim() == "" || ratingValue == null
               || comment.trim() == "" || comment == null) {
            alert("输入为空！") ;
            return ;
        }
        console.log("ratingValue: " + ratingValue + ", comment:" + comment ) ;
        // parameter string
        var action = "doRate" ;
        var paramStr = action + "&" + ratingValue + "&" + comment ;
        // 2. create xhr
        var xhr = createXMLRequest() ;
        // 3. configure xhr: post request
        xhr.open(
            "POST",
            "/01_jspBasics/test/nativeAjax"
        )

        // 4. call back
           // 4.1 rendering data
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if(xhr.status == 200) {
                    var $show = document.getElementById("showMsg") ;
                    console.log("got : " + xhr.responseText) ;
                    $show.innerHTML = xhr.responseText ;
                    $show.style.display = "";
                } else {
                    alert("处理异常！")
                }
            }


        }
        //5. send : for POST, the paramerStr should be used in send method.
        xhr.send(paramStr) ;

    }

    /**
     * @function: do rate but pass data in json string.
     */
    function doRateInJson() {
        // 1. preparing parameters
        var $ratingForm = document.getElementById("rating-form");
        var ratingValue  ;
        // got rating value
        $ratingForm.rating.forEach(function(item,index) {
            if (item.checked) {
                ratingValue = item.value ;
            }
        })
        // got comment value
        var comment = document.getElementById("comment").value ;

        if (ratingValue.trim() == "" || ratingValue == null
            || comment.trim() == "" || comment == null) {
            alert("输入为空！") ;
            return ;
        }
        var action = "doRateByJSON"
        var ratingForm = {
            'ratingValue':ratingValue,
            'comment': comment,
            'action' : action
        }

        // 2. create xhr
        var xhr = createXMLRequest() ;
        // 3. configure xhr: post request
        xhr.open(
            "POST",
            "/01_jspBasics/test/nativeAjax"
        )

        // 4. call back
        // 4.1 rendering data
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if(xhr.status == 200) {
                    var $show = document.getElementById("showMsg") ;
                    // parse the response data.
                    console.log("got : " + xhr.responseText) ;
                    var respObj = JSON.parse(xhr.responseText) ;
                    console.log(respObj) ;
                    $show.innerHTML = respObj.ratingValue + " <br> " + respObj.comment ;
                     $show.style.display = "";
                } else {
                    alert("处理异常！")
                }
            }


        }
        //5. send : for POST, the paramerStr should be used in send method.
        // the ratingForm needs to be serialized.
        var ratingFormJsonStr = JSON.stringify(ratingForm) ;
        console.log("ratingForm: " + ratingFormJsonStr) ;
        xhr.send(ratingFormJsonStr) ;




    }





</script>


</body>
</html>
